package com.jds.test.bio.p11;

/**
 * https://www.cnblogs.com/silyvin/articles/12064484.html
 * https://www.cnblogs.com/silyvin/articles/12070767.html
 * Created by joyce on 2019/11/26.
 */
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static final int PORT = 12123;
    public static final int BUFFER_SIZE = 1024;

    public static void main(String [] f) {
        try {
            new Server().server(f.length == 0 ? "1":f[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //服务端代码
    public void server(String flag) throws IOException, InterruptedException{
        System.out.println(flag);
        ServerSocket ss = new ServerSocket(PORT);
        while(true) {
            Socket s = ss.accept();

            s.getOutputStream().write("hello ".getBytes());
            s.getOutputStream().flush();

            Thread.sleep(5000);

            // 没什么鸟用
            System.out.println(s.isClosed());

            if("2".equals(flag)) {
                s.getOutputStream().write(1);
                s.getOutputStream().flush();
            }

            if("3".equals(flag)) {
                s.getOutputStream().write(1);
                s.getOutputStream().flush();
                Thread.sleep(2000);
                s.getOutputStream().write(2);
            }

            while (s.getInputStream().read(new byte[BUFFER_SIZE]) != -1) {
                ;
            };
            /**
             * 显示close，发出fin包
             */
            s.close();
        }
    }
}